#!/bin/bash

# Spring MVC字数统计项目 - Tomcat启动脚本

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 设置项目路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TOMCAT_DIR="$SCRIPT_DIR/.tomcat"
DIST_DIR="$SCRIPT_DIR/dist"

# 设置Tomcat根路径
TOMCAT_HOME="/Users/liuyu/Workbench/Sources/05Deploy/apache-tomcat-9.0.43"

echo -e "${BLUE}================================${NC}"
echo -e "${BLUE}  Spring MVC字数统计项目启动器${NC}"
echo -e "${BLUE}================================${NC}"

# 检查编译状态
if [ ! -f "$DIST_DIR/WEB-INF/classes/com/wordcounter/controller/WordCounterController.class" ]; then
    echo -e "${RED}错误：请先编译项目！${NC}"
    echo -e "${YELLOW}运行命令：./build.sh${NC}"
    exit 1
fi

# 检查Tomcat目录
if [ ! -d "$TOMCAT_DIR" ]; then
    echo -e "${RED}错误：找不到Tomcat配置目录：$TOMCAT_DIR${NC}"
    exit 1
fi

# 检查Tomcat可执行文件
if [ ! -f "$TOMCAT_HOME/bin/catalina.sh" ]; then
    echo -e "${RED}错误：找不到Tomcat可执行文件：$TOMCAT_HOME/bin/catalina.sh${NC}"
    echo -e "${YELLOW}请检查Tomcat安装路径是否正确${NC}"
    exit 1
fi

echo -e "${GREEN}✓ 找到Tomcat: $TOMCAT_HOME${NC}"

# 设置环境变量
export CATALINA_HOME="$TOMCAT_HOME"
export CATALINA_BASE="$TOMCAT_DIR"
export CATALINA_OPTS="-Dcatalina.home=$TOMCAT_HOME -Dcatalina.base=$TOMCAT_DIR"

# 加载项目特定的环境配置
if [ -f "$TOMCAT_DIR/bin/setenv.sh" ]; then
    echo -e "${BLUE}加载环境配置...${NC}"
    source "$TOMCAT_DIR/bin/setenv.sh"
fi

# 创建必要的目录
mkdir -p "$TOMCAT_DIR/logs"
mkdir -p "$TOMCAT_DIR/temp"
mkdir -p "$TOMCAT_DIR/work"

echo -e "${GREEN}✓ 环境配置完成${NC}"
echo -e "${BLUE}项目路径: $SCRIPT_DIR${NC}"
echo -e "${BLUE}Tomcat路径: $TOMCAT_HOME${NC}"
echo -e "${BLUE}应用路径: $DIST_DIR${NC}"
echo -e "${BLUE}访问地址: http://localhost:8080/wordcounter${NC}"
echo ""

# 启动Tomcat
echo -e "${YELLOW}正在启动Tomcat...${NC}"
echo -e "${YELLOW}按 Ctrl+C 停止服务器${NC}"
echo ""

cd "$TOMCAT_HOME/bin"
./catalina.sh run 